<template>
  <div class="city-weather">
    <div class="left" @click="Select">
      {{ city }} <i class="iconfont icon-triangle-up"></i>
    </div>
    <div class="right">
      <p>{{ weathers }}</p>
      <p>{{ template }}</p>
    </div>
  </div>

  <!-- 展示框 -->
  <div class="show-box" v-show="boxshow">
    <div class="show-title">
      当前城市: {{ city }} <i @click="Closebtn" class="iconfont icon-close"></i>
    </div>

    <div class="hot-city">
      <span @click="handleclick(hotcity)" v-for="hotcity in hotcitys" :key="hotcity">{{ hotcity }}</span>
    </div>

    <div class="searchinput">
      <div class="left">
        <el-button-group>
          <el-button @click="ProvinceSearch">按省份</el-button>
          <el-button @click="CitySearch">按城市</el-button>
        </el-button-group>
      </div>
      <div class="right">
        <el-input :prefix-icon="Search" placeholder="搜索城市" v-model="cityname"></el-input>
      </div>
    </div>

    <div class="provincesearch" v-if="showProvinceSearch">
      <div class="ZMsearch">
        <!-- 字母导航栏，添加点击事件 -->
        <span
          v-for="(ZMP, index) in ZMPs"
          :key="index"
          @click="scrollToLetter(ZMP)"
          style="cursor: pointer"
          :class="{ active: currentLetter === ZMP }"
        >
          {{ ZMP }}
        </span>
      </div>

      <div class="specific-province">
        <div
          v-for="(provincedata, index) in provincedatas"
          :key="index"
          class="province-item"
          :id="`province-${provincedata.pinyinInitial}`"
        >
          <div class="left">{{ provincedata.label }}:</div>
          <div class="right">
            <span @click="handleclick(city.label)" v-for="(city, cityIndex) in provincedata.children" :key="cityIndex">
              {{ city.label }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <div class="citysearch" v-if="showCitySearch">
      <div class="ZMsearch">
        <span 
          v-for="(ZMC, index) in ZMCs" 
          :key="index"
          @click="scrollToCityLetter(index)"
          style="cursor: pointer"
        >
          {{ ZMC }}
        </span>
      </div>

      <div class="specific-city">
        <div class="city-item" v-for="(ZMC, index) in ZMCs" :key="index" :id="`city-letter-${index}`">
          <div class="left">{{ ZMC }}: </div>
          <div class="right">
            <span @click="handleclick(city)" v-for="(city, cityIndex) in citydatas[index]" :key="cityIndex">
              {{ city }}
            </span>
          </div>
        </div>
      </div>
    </div>

   <div class="inputlist"  v-show="isinputlist">
         <ul >
             <li @click="handleinputlist(city)" v-for="city in inputlist"> <i class="iconfont icon-seartch"></i>{{ city }}</li>
         </ul>
   </div>

  </div>
</template>

<script setup>
import { ref, nextTick,inject,watch,onMounted} from 'vue'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'

// 注入地图实例
const { Amap, map } = inject('mapandAmap')
let weathers = ref('')
let template = ref('')
let city = ref('')

// 响应式数据
let cityname = ref('')
let provincedatas = ref([])
let citydatas = ref([])
let boxshow = ref(false)
let showProvinceSearch = ref(true)
let showCitySearch = ref(false)
let currentLetter = ref('') // 当前选中的字母
 let allcitys = [];
 let inputlist = ref([]);
 let isinputlist = ref(false);




 console.log(allcitys)
watch([Amap, map, city], ([Amap, map, citys])=>{

  if(citys){
         var placeSearch = new Amap.PlaceSearch({
    //city 指定搜索所在城市，支持传入格式有：城市名、citycode 和 adcode
    city: "全国",
    map: map,
   
  });
 
  placeSearch.search(citys)
  placeSearch.clear();

  
  // 天气查询
   //创建天气查询实例
  var weather = new Amap.Weather();
  //执行实时天气信息查询
  weather.getForecast(citys, function (err, data) {
    weathers.value = data.forecasts[0].dayWeather
    console.log(data.forecasts[0])

    template.value = `${data.forecasts[0].nightTemp}℃-${data.forecasts[0].dayTemp}℃`
    
    //err 正确时返回 null
    //data 返回实时天气数据，返回数据见下表
  });
  }
  

  // 点击map,收起show-box框
  map.on('click', () => {
      boxshow.value = false;
  })

 // // 城市定位
  if (!citys) { 
     var citySearch = new Amap.CitySearch()
  citySearch.getLocalCity(function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // 查询成功，result即为当前所在城市信息
      console.log(result.city)
      city.value = result.city;
    }
  })
  }



})

// inputlist搜索框
watch(cityname, (value) => {
  if (value) {
    isinputlist.value = true;
    inputlist.value = allcitys.filter(city => city.includes(value))
  }else{
    isinputlist.value = false;
  }
})

// 获取拼音首字母
const getFirstLetter = (chinese) => {
  const pinyinMap = {
      安徽省: 'A',
    福建省: 'F',
    甘肃省: 'G',
    广东省: 'G',
    广西省: 'G',
    贵州省: 'G',
    海南省: 'H',
    河北省: 'H',
    河南省: 'H',
    黑龙江省: 'H',
    湖北省: 'H',
    湖南省: 'H',
    吉林省: 'J',
    江苏省: 'J',
    江西省: 'J',
    辽宁省: 'L',
    内蒙古: 'N',
    宁夏省: 'N',
    青海省: 'Q',
    山东省: 'S',
    山西省: 'S',
    陕西省: 'S',
    上海省: 'S',
    四川省: 'S',
    台湾省: 'T',
    天津省: 'T',
    西藏: 'X',
    新疆: 'X',
    云南省: 'Y',
    浙江省: 'Z',
  };

  return pinyinMap[chinese] || '#';
};

// 加载城市数据
const loadCityData = async () => {
  try {
    const response = await axios('http://project.x-zd.net:3001/apis/citylist');
    provincedatas.value = response.data.data
      .filter(item => item.children.length > 4)
      .sort((a, b) => a.label.localeCompare(b.label))
      .map(province => ({
        ...province,
        pinyinInitial: getFirstLetter(province.label)
      }));

   
    response.data.data.forEach(item => {
      item.children.forEach(city => {
        allcitys.push(city.label);
      });
    });

    // 去重并排序
    allcitys.sort((a, b) => a.localeCompare(b));

    // 城市分组（保持原有逻辑）
    citydatas.value[0] = allcitys.slice(0, 12);
    citydatas.value[1] = allcitys.slice(12, 33);
    citydatas.value[2] = allcitys.slice(33, 51);
    citydatas.value[3] = allcitys.slice(51, 68);
    citydatas.value[4] = allcitys.slice(68, 71);
    citydatas.value[5] = allcitys.slice(71, 78);
    citydatas.value[6] = allcitys.slice(78, 90);
    citydatas.value[7] = allcitys.slice(90, 127);
    citydatas.value[8] = allcitys.slice(127, 153);
    citydatas.value[9] = allcitys.slice(153, 158);
    citydatas.value[10] = allcitys.slice(158, 190);
    citydatas.value[11] = allcitys.slice(190, 197);
    citydatas.value[12] = allcitys.slice(197, 211);
    citydatas.value[13] = allcitys.slice(211, 221);
    citydatas.value[14] = allcitys.slice(221, 237);
    citydatas.value[15] = allcitys.slice(237, 239);
    citydatas.value[16] = allcitys.slice(239, 270);
    citydatas.value[17] = allcitys.slice(270, 293);
    citydatas.value[18] = allcitys.slice(273, 311);
    citydatas.value[19] = allcitys.slice(311, 337);
    citydatas.value[20] = allcitys.slice(337, 364);
    citydatas.value[21] = allcitys.slice(364, 371);

    // 处理额外的城市
    allcitys.forEach((city, index) => {
      if (index > 374) {
        citydatas.value[21].push(city);
      }
      if (index >= 371 && index <= 373) {
        citydatas.value[2].push(city);
      }
    });
  } catch (error) {
    console.error('获取城市数据失败:', error);
  }
};


// 点击字母导航滚动到对应位置
const scrollToLetter = async (letter) => {
  currentLetter.value = letter;
  await nextTick(); // 等待DOM更新
  
  const element = document.getElementById(`province-${letter}`);
  if (element) {
    // 平滑滚动到元素位置
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
};

// 城市字母导航滚动
const scrollToCityLetter = async (index) => {
  await nextTick();
  const element = document.getElementById(`city-letter-${index}`);
  if (element) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
};

// 初始化加载数据
loadCityData();


function handleclick(cityname){
  boxshow.value = false;
    city.value = ''
  city.value = cityname
  console.log(city.value)
  
}

function handleinputlist(inputcity){
  boxshow.value = false;
    city.value = ''
  console.log(inputcity)
     city.value = inputcity
}

// 事件处理函数
function Select() {
  boxshow.value = !boxshow.value;
}

function ProvinceSearch() {
  showProvinceSearch.value = true;
  showCitySearch.value = false;
}

function CitySearch() {
  showProvinceSearch.value = false;
  showCitySearch.value = true;
}

function Closebtn() {
  boxshow.value = false;
}

// 常量定义
const hotcitys = [
  '全国', '北京', '天津', '沈阳', '大连', '上海', '南京', '苏州', '杭州', '青岛',
  '郑州', '武汉', '长沙', '广州', '深圳', '重庆', '成都', '西安', '香港', '澳门'
];
const ZMPs = ['A', 'F', 'G', 'H', 'J', 'L', 'N', 'Q', 'S', 'T', 'X', 'Y', 'Z'];
const ZMCs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'];
</script>

<style lang="scss" scoped>
@import 'reset-css';
.city-weather {
  display: flex;
  position: fixed;
  padding: 5px;
  top: 40px;
  left: 670px;
  height: 55px;
  width: 180px;
  background-color: rgb(255, 255, 255);
  color: rgb(95, 100, 119);
  font-size: 17px;
  font-weight: 500;

  .left {
    text-align: center;
    height: 100%;
    width: 50%;
    line-height: 55px;
  }
  .left:hover {
    color: rgb(102, 153, 255);
    cursor: pointer;
  }

  .right {
    margin-top: 5px;
    font-size: 15px;
    text-align: center;
    height: 100%;
    width: 50%;
  }
  .right:hover {
    color: rgb(102, 153, 255);
    cursor: pointer;
  }
}

.show-box {
  position: fixed;
  top: 110px;
  left: 670px;
  padding: 20px;
  width: 580px;
  background-color: rgb(255, 255, 255);
  font-size: 15px;
  font-weight: 500;
  color: rgb(95, 100, 119);

  .show-title {
    font-size: 15px;
    font-weight: 500;
    border-bottom: 1px solid rgb(221, 221, 221);
    padding-bottom: 10px;

    .icon-close {
      float: right;
      font-size: 20px;
    }
    .icon-close:hover {
      color: rgb(102, 153, 255);
    }
  }

  .hot-city {
    height: 80px;
    line-height: 35px;

    span {
      padding: 4px;
      color: rgb(102, 153, 255);
    }
    span:hover {
        color: rgb(102, 153, 255);
        cursor: pointer;
    }
  }

  .searchinput {
    display: flex;
    justify-content: space-between;
    height: 40px;
    line-height: 40px;

    .left {
      .el-button-group {
        .el-button {
          font-size: 13px;
          font-weight: 500;
          color: rgb(95, 100, 119);
          width: 100px;
          height: 35px;
        }
      }
    }
   
  }

  .provincesearch {
    height: 210px;

    .ZMsearch {
      height: 25px;
      line-height: 25px;

      span {
        display: inline-block;
        text-align: center;
        margin: 0 5px;
        width: 20px;
        background-color: rgb(245, 245, 245);
        color: rgb(95, 100, 119);
      }
      span:hover {
        color: rgb(102, 153, 255);
        cursor: pointer;
      }
      span.active {
        color: rgb(102, 153, 255);
        font-weight: bold;
      }
    }

    .specific-province {
      height: 200px;
      overflow-y: scroll;

      .province-item {
        margin-top: 15px;
        display: flex;

        .left {
          text-align: center;
          font-size: 13px;
          font-weight: 600;
          width: 12%;
        }
        .right {
          width: 88%;
          text-align: left;
          color: rgb(177, 177, 177);
          font-size: 13px;
          font-weight: 500;

          span {
            margin: 0 5px;
          }
          span:hover {
            color: rgb(102, 153, 255);
            cursor: pointer;
          }
        }
      }
    }
  }

  .citysearch {
    height: 210px;

    .ZMsearch {
      height: 50px;
      line-height: 25px;

      span {
        display: inline-block;
        text-align: center;
        margin: 0 5px;
        width: 20px;
        background-color: rgb(245, 245, 245);
        color: rgb(95, 100, 119);
      }
      span:hover {
        color: rgb(102, 153, 255);
        cursor: pointer;
      }
    }

    .specific-city {
      height: 180px;
      overflow-y: scroll;

      .city-item {
        margin-top: 15px;
        display: flex;

        .left {
          width: 3%;
          margin-right: 10px;
        }
        .right {
          width: 97%;

          span {
            display: inline;
            font-size: 13px;
            font-weight: 500;
            color: rgb(174, 174, 174);
            margin-right: 10px;
          }
          span:hover {
            color: rgb(102, 153, 255);
            cursor: pointer;
          }
        }
      }
    }
  }


  .inputlist{
    position: absolute;
    top: 170px;
    right: 20px;
    width: 235px;
    background-color: rgb(255, 255, 255);
    border: 1px  solid #ccc;
    border-top: 0px;

   ul{
    li{
      margin-left: 10px;
       height: 25px;
         cursor: pointer;
       i{
        margin-right: 10px;
       
       }
    }
   }
  }
}
</style>